package com.yzf.wisecoder.wisecodercommon.response;

import lombok.Data;
import lombok.ToString;
import lombok.experimental.Accessors;

import java.io.Serializable;

/**
 * @author jianghuiyong
 * @Description 响应实体
 * @date 2020/5/7 16:38
 */
@Data
@Accessors(chain = true)
@ToString
public class Response<T> implements Serializable {

    private Boolean success;

    private int errorCode;

    private String errorMessage;

    private T data;

    public Response(int errorCode, String errorMessage, T data, boolean success) {
        this.errorCode = errorCode;
        this.errorMessage = errorMessage;
        this.data = data;
        this.success = success;
    }

    protected Response(int errorCode, String errorMessage, boolean success) {
        if (errorCode < 0) {
            throw new IllegalArgumentException("响应码错误");
        }
        this.errorCode = errorCode;
        this.errorMessage = errorMessage;
        this.success = success;
    }

    /**
     * 构建成功返回响应
     *
     * @param <T>
     * @return
     */
    public static <T> Response<T> buildSuccessResponse() {
        return new Response(ErrorCode.ResponseErrorCode.OK.getCode(), ErrorCode.ResponseErrorCode.OK.getMsg(), Boolean.TRUE);
    }

    /**
     * 按单个实体构建响应
     *
     * @param data
     * @param <T>
     * @return
     */
    public static <T> Response<T> buildSuccessResponseWithData(T data) {
        return new Response(ErrorCode.ResponseErrorCode.OK.getCode(), ErrorCode.ResponseErrorCode.OK.getMsg(), Boolean.TRUE).setData(data);
    }

    /**
     * 构建错误响应实体
     *
     * @param errorMessage
     * @return
     */
    public static Response buildErrorResponse(String errorMessage) {
        return new Response(ErrorCode.ResponseErrorCode.INTERNALERROR.getCode(), errorMessage, Boolean.FALSE);
    }

    /**
     * 构建错误响应实体
     *
     * @param errorCode
     * @param errorMessage
     * @return
     */
    public static Response buildErrorResponse(int errorCode, String errorMessage) {
        return new Response(errorCode, errorMessage, Boolean.FALSE);

    }

}
